package de.lindenvalley.ergo.drag;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

import util.AnotherFont;
import util.PointUtil;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Matrix;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import de.lindenvalley.ergo.CameraActivity;
import de.lindenvalley.ergo.ContactActivity;
import de.lindenvalley.ergo.ErgoAppActivity;
import de.lindenvalley.ergo.R;
import de.lindenvalley.ergo.content.Round;
import de.lindenvalley.ergo.drag.MyAbsoluteLayout.LayoutParams;
import de.lindenvalley.ergo.view.GraphView;

/**
 * This activity presents two images and a text view and allows them to be dragged around.
 * Press and hold on a view initiates a drag. 
 *
 * <p> This activity is derviced from the Android Launcher class.
 * 
 */

public class DragActivity extends Activity implements View.OnTouchListener
{


private DragController mDragController;   // Object that sends out drag-drop events while a view is being moved.
private DragLayer mDragLayer;             // The ViewGroup that supports drag-drop.
public static final int[] points = new int[]{R.id.imageViewBigRound, R.id.imageView2, R.id.imageView3, R.id.imageView4, R.id.imageView5, R.id.imageView6, R.id.imageView7};
public static int POINT_HALF_WIDTH = 0;

public static final boolean Debugging = false;

float[] mirrorY = 
{  -1, 0, 0, 
	0, 1, 0,  
	0, 0, 1    
};
Matrix matrixMirrorY = new Matrix();
Matrix matrix = new Matrix();
int displayWidth, displayHeight;
GraphView graphView;
private boolean isReverse;



/**
 * onCreate - called when the activity is first created.
 * 
 * Creates a drag controller and sets up three views so click and long click on the views are sent to this activity.
 * The onLongClick method starts a drag sequence.
 *
 */

 protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    mDragController = new DragController(this);
    Display display = getWindow().getWindowManager().getDefaultDisplay();
    displayWidth = display.getWidth();
    displayHeight = display.getHeight();
    
    matrixMirrorY.setValues(mirrorY);
    matrix.postConcat(matrixMirrorY);
    
    int panelHeight = ((BitmapDrawable)getResources().getDrawable(R.drawable.panel)).getBitmap().getHeight();
    mDragController.getPoints().put(points[0], new Point((int) (displayWidth / 3.5), (displayHeight - 80) / 8));
    mDragController.getPoints().put(points[1], new Point((int) (displayWidth / 3.5), (int) ((displayHeight - 80) / 3.5)));
    mDragController.getPoints().put(points[2], new Point((int) (displayWidth / 3.5), (int) ((displayHeight - 80) / 1.5)));
    mDragController.getPoints().put(points[3], new Point((int) (displayWidth / 1.5), (int) ((displayHeight - 80) / 1.5)));
    mDragController.getPoints().put(points[4], new Point((int) (displayWidth / 1.5), (int) ((displayHeight - (panelHeight + 100)))));
    mDragController.getPoints().put(points[5], new Point((int) (displayWidth / 3), (int) (displayHeight/2 -40)));
    mDragController.getPoints().put(points[6], new Point((int) (displayWidth / 1.5), (int) (displayHeight/2 -40)));

    setContentView(R.layout.camera_points_panel);
    
    AnotherFont.findTypeface((ViewGroup)getWindow().getDecorView());
    
    graphView = (GraphView) findViewById(R.id.graphPreview);
    graphView.setDragController(mDragController);
    mDragController.setGraphView(graphView);
	Options options = new Options();
	options.inSampleSize = 2;
//	FileInputStream stream;
//	Bitmap bitmap = null;
	
	View v = null;
    
    v = findViewById(R.id.switcherStart);
    v.setOnTouchListener(this);
    
    v = findViewById(R.id.switcherRotate);
    v.setOnTouchListener(this);
    
    v = findViewById(R.id.switcherContact);
    v.setOnTouchListener(this);
    
    v = findViewById(R.id.switcherInfo);
    v.setOnTouchListener(this);
    
    v = findViewById(R.id.imageViewLogo);
    v.setOnTouchListener(this);
    
    String fileString = getIntent().getStringExtra("file");
    if (fileString != null){
		ImageView iv = (ImageView) findViewById(R.id.imagePreview);
//		iv.setImageURI(Uri.parse(fileString));
//    	View iv = (View) findViewById(R.id.layoutPreview);
    	FileInputStream fin;
		try {
			fin = new FileInputStream(fileString);
			BitmapDrawable drawable = new BitmapDrawable(fin);
        	iv.setBackgroundDrawable(drawable);
        	fin.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    }

    setupViews ();
    
}



/**
 * Start dragging a view.
 *
 */    

public boolean startDrag (View v)
{
    // Let the DragController initiate a drag-drop sequence.
    // I use the dragInfo to pass along the object being dragged.
    // I'm not sure how the Launcher designers do this.
    Object dragInfo = v;
    if (v.getTag() instanceof Round && ((Round)v.getTag()).isFixed()){
    	Round round = (Round)v.getTag();
    	round.setFixed(false);
    	ImageView iv = (ImageView) v;
    	if (round.isBig())
    		iv.setImageResource(R.drawable.round_red_big);
    	else
    		iv.setImageResource(R.drawable.round_red_small);
    }
    mDragController.startDrag (v, mDragLayer, dragInfo, DragController.DRAG_ACTION_MOVE);
    return true;
}

/**
 * Finds all the views we need and configure them to send click events to the activity.
 *
 */
private void setupViews() 
{
    DragController dragController = mDragController;

    mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
    mDragLayer.setDragController(dragController);
    dragController.addDropTarget (mDragLayer);

    for (int i : points){
    	ImageView i1 = (ImageView) findViewById (i);
    	i1.setOnTouchListener(this);
//    	i1.setOnLongClickListener(this);
    	Round round = new Round();
    	if (i == R.id.imageViewBigRound){
    		round.setBig(true);
    	}
    	i1.setTag(round);
    	MyAbsoluteLayout.LayoutParams lp = (MyAbsoluteLayout.LayoutParams) i1.getLayoutParams();
    	Point point = mDragController.getPoints().get(i1.getId());
    	lp.x = point.x;
    	lp.y = point.y;
    	mDragLayer.updateViewLayout(i1, lp);
    	
    }
		ImageView imageStol = (ImageView) findViewById(R.id.imageViewStol);
		MyAbsoluteLayout.LayoutParams lp = (LayoutParams) imageStol
				.getLayoutParams();
		lp.y = displayHeight/2;
		lp.x = displayWidth - ((BitmapDrawable)imageStol.getDrawable()).getBitmap().getWidth();
		mDragLayer.updateViewLayout(imageStol, lp);
		imageStol.setOnTouchListener(this);

		ImageView imageLogo = (ImageView) findViewById(R.id.imageViewLogo);
		lp = (LayoutParams) imageLogo.getLayoutParams();
		lp.x = displayWidth
				- ((BitmapDrawable) imageLogo.getDrawable()).getBitmap()
						.getWidth() - 20;
		lp.y = 20;
		mDragLayer.updateViewLayout(imageLogo, lp);

		TextView textMessage = (TextView) findViewById(R.id.textViewMessage);
		lp = (LayoutParams) textMessage.getLayoutParams();
		int messageHeight = ((BitmapDrawable) textMessage.getBackground())
				.getBitmap().getHeight();
		lp.y = (int) (displayHeight - messageHeight - getResources().getDimension(R.dimen.text_two_bottom));
		lp.x = 25;
		lp.width = displayWidth - 50;
		
		mDragLayer.updateViewLayout(textMessage, lp);
		textMessage.setOnTouchListener(this);

    

//    Toast.makeText (getApplicationContext(), 
//                    "Press and hold to drag a view", Toast.LENGTH_LONG).show ();

}



/**
 * Show a string on the screen via Toast.
 * 
 * @param msg String
 * @return void
 */

public void toast (String msg)
{
    Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_SHORT).show ();
} // end toast

/**
 * Send a message to the debug log and display it using Toast.
 */

public void trace (String msg) 
{
    if (!Debugging) return;
    Log.d ("DragActivity", msg);
    toast (msg);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
	int id = v.getId();
	Map<Integer,Point> points = mDragController.getPoints();
	boolean result = false;
	switch (id){
		case R.id.resultToast:
		case R.id.textViewMessage:
//			if (event.getAction() == MotionEvent.ACTION_UP){
			v.setVisibility(View.GONE);
//			}
			break;
		case R.id.switcherStart:
			if (event.getAction() == MotionEvent.ACTION_UP){
				Intent intent = new Intent(this, ErgoAppActivity.class);
				startActivity(intent);
				finish();
			}
			break;
		case R.id.switcherRotate:
			if (event.getAction() == MotionEvent.ACTION_UP){
				for (int i : DragActivity.points){
			    	ImageView i1 = (ImageView) findViewById (i);
			    	MyAbsoluteLayout.LayoutParams lp = (MyAbsoluteLayout.LayoutParams) i1.getLayoutParams();
			    	Point point = mDragController.getPoints().get(i1.getId());
			    	int x = displayWidth - point.x;
			    	if (x > displayWidth){
			    		x = displayWidth;
			    	}
			    	if (x < 0){
			    		x = 0;
			    	}
			    		
			    	lp.x = x;
			    	point.x = x;
			    	mDragLayer.updateViewLayout(i1, lp);
			    }
				ImageView stol = (ImageView) findViewById(R.id.imageViewStol);
				Bitmap bi = ((BitmapDrawable)stol.getDrawable()).getBitmap();
				Matrix matrix = new Matrix();
				matrix.postRotate(180);
				stol.setImageBitmap(Bitmap.createBitmap(bi, 0, 0, bi.getWidth(), bi.getHeight(), matrix, true));
				
				MyAbsoluteLayout.LayoutParams lp = (MyAbsoluteLayout.LayoutParams) stol.getLayoutParams();
				if (!isReverse){
					lp.x = 0;
				} else {
					lp.x = displayWidth - bi.getWidth();
				}
				isReverse = !isReverse;
				mDragLayer.updateViewLayout(stol, lp);
				bi.recycle();
				
			}
			result = true;
			break;
			
		case R.id.switcherContact:
			if (event.getAction() == MotionEvent.ACTION_UP){
				Intent intent = new Intent(this, ContactActivity.class);
				startActivity(intent);
//				finish();
			}
			break;
			
		case R.id.imageViewLogo:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				Intent intent = new Intent (Intent.ACTION_VIEW, Uri.parse(getString(R.string.urlLink)));
				startActivity(intent);
			}
		case R.id.switcherInfo:
			if (event.getAction() == MotionEvent.ACTION_UP){
				Point pointKnee = points.get(DragActivity.points[3]);
				Point aKnee = points.get(DragActivity.points[2]);
				Point cKnee = points.get(DragActivity.points[4]);
				Point a_Knee = PointUtil.getVectorCoordinate(pointKnee, aKnee);
				Point c_Knee = PointUtil.getVectorCoordinate(pointKnee, cKnee);
				double angleKnee = PointUtil.getAngle(a_Knee, c_Knee);
				
				Point pointElbow = points.get(DragActivity.points[5]);
				Point aElbow = points.get(DragActivity.points[1]);
				Point cElbow = points.get(DragActivity.points[6]);
				Point a_Elbow = PointUtil.getVectorCoordinate(pointElbow, aElbow);
				Point c_Elbow = PointUtil.getVectorCoordinate(pointElbow, cElbow);
				double angleElbow = PointUtil.getAngle(a_Elbow, c_Elbow);
				
				Point pointNeck = points.get(DragActivity.points[1]);
				Point aNeck = points.get(DragActivity.points[0]);
				Point cNeck = points.get(DragActivity.points[2]);
				Point a_Neck = PointUtil.getVectorCoordinate(pointNeck, aNeck);
				Point c_Neck = PointUtil.getVectorCoordinate(pointNeck, cNeck);
				double angleNeck = PointUtil.getAngle(a_Neck, c_Neck);
				
				StringBuilder sb = new StringBuilder();
				boolean isOk  = false;

				Log.i("---------", "ANGLE ELBOW " + angleElbow + ", ANGLE KNEE " + angleKnee + ", ANGLE NECK " + angleNeck);
				View stolView = findViewById(R.id.imageViewStol);
				int stolYposition = stolView.getTop();
				
				if (stolYposition < pointElbow.y || stolYposition < cElbow.y 
						|| stolYposition > aKnee.y || stolYposition > pointKnee.y || stolYposition > cKnee.y || pointKnee.y > cKnee.y){
					sb.append(getString(R.string.incorrect_body_position));
				} else	if (angleElbow <= 85 && angleKnee >= 95){
					sb.append(getString(R.string.chair_desk_high));
				} else if (angleElbow > 100 && angleKnee < 80) {
					sb.append(getString(R.string.chair_desk_low));
				} else if (angleElbow <= 85 && angleKnee < 80){
					sb.append(getString(R.string.chair_low_desk_high));
				} else if (angleElbow > 100 && angleKnee >= 95){
					sb.append(getString(R.string.chair_high_desk_low));
				} else if (angleKnee >= 95){
					sb.append(getString(R.string.chair_high));
				} else if (angleKnee < 80){
					sb.append(getString(R.string.chair_low));
				} else if (angleElbow <= 85){
					sb.append(getString(R.string.table_high));
				} else if (angleElbow > 100){
					sb.append(getString(R.string.table_low));
				} else if (angleNeck < 160){
					sb.append(getString(R.string.anatomically_fail));
				} else {
					sb.append(getString(R.string.all_ok));
					isOk = true;
				}
				
				View view = findViewById(R.id.textViewMessage);
				view.setVisibility(View.GONE);
				
				view = findViewById(R.id.resultToast);
				AnotherFont.findTypeface((ViewGroup)view);
				ImageView iv = (ImageView) view.findViewById(R.id.resultImageView);
				TextView tv = (TextView) view.findViewById(R.id.resultTextView);
				
				if (isOk){
					iv.setImageResource(R.drawable.icon_ok);
				} else {
					iv.setImageResource(R.drawable.icon_warning);
				}
				tv.setText(sb.toString());
				MyAbsoluteLayout.LayoutParams lp =  (LayoutParams) view.getLayoutParams();
				BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.bg_result);
				Bitmap bitmap = drawable.getBitmap();
				lp.x = (displayWidth - bitmap.getWidth())/2;
				lp.y = (int) (displayHeight - bitmap.getHeight() - getResources().getDimension(R.dimen.text_two_bottom));
				view.setOnTouchListener(this);
				view.setVisibility(View.VISIBLE);

			}
			break;
			
			
		default:
			if (v instanceof ImageView && 
					MotionEvent.ACTION_DOWN == event.getAction() ){
				if (!v.isInTouchMode()) {
			        toast ("isInTouchMode returned false. Try touching the view again.");
			        result =  false;
			     }
				
			    if ((v.getTag() instanceof Round && !((Round)v.getTag()).isFixed()) || v.getId() == R.id.imageViewStol){ 
			    	result =  startDrag (v);
			    } else {
			    	return true;
			    }
			    
			}
			
	}
	if (v instanceof TextSwitcher && event.getAction() != MotionEvent.ACTION_MOVE){
		((TextSwitcher)v).showNext();
		result = true;
	}
	if (v instanceof ImageView 
			&& v.getTag() instanceof Round 
			&& (MotionEvent.ACTION_CANCEL == event.getAction() || MotionEvent.ACTION_UP == event.getAction())){
			Round round = (Round)v.getTag();
			long clickTime = event.getEventTime() - round.getLastTimeClick();
			
			round.setLastTimeClick(event.getEventTime());
//			Log.i("--------------------", clickTime +"");
			if (clickTime <= 750){
				round.setFixed(!round.isFixed());
				if (round.isFixed()){
		        	if (round.isBig()){
		        		((ImageView) v).setImageResource(R.drawable.round_green_big);	
		        	} else {
		        		((ImageView) v).setImageResource(R.drawable.round_green_small);
		        	}
				} else {
					if (round.isBig()){
		        		((ImageView) v).setImageResource(R.drawable.round_red_big);	
		        	} else {
		        		((ImageView) v).setImageResource(R.drawable.round_red_small);
		        	}
				}
			}
	}
	
	return result;
	
}


} // end class
